package com.zzzyh.forumsystemclient.services.impl;

import com.zzzyh.forumsystemclient.dao.NoticeMapper;
import com.zzzyh.forumsystemclient.dao.NotificationsMapper;
import com.zzzyh.forumsystemclient.dao.UserMapper;
import com.zzzyh.forumsystemclient.model.Article;
import com.zzzyh.forumsystemclient.model.Notifications;
import com.zzzyh.forumsystemclient.model.User;
import com.zzzyh.forumsystemclient.services.IArticleService;
import com.zzzyh.forumsystemclient.services.INotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class NotificationServiceImpl implements INotificationService {
    @Autowired
    private NotificationsMapper notificationsMapper;
    @Autowired
    private IArticleService articleService;
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<Notifications> notifications(Integer pageNum, Integer pageSize, String type,Integer userId) {
        List<Notifications> notifications = notificationsMapper.notifications(pageNum, (pageNum - 1) * pageSize, type, userId);
        for (Notifications notification :
                notifications) {
            if (notification.getFromUserId() != null){
                User fromUser = userMapper.selectByPrimaryKey(Math.toIntExact(notification.getFromUserId()));
                notification.setFromNickName(fromUser.getNickname());
            }
            if (notification.getUserId() != null){
                User toUser = userMapper.selectByPrimaryKey(Math.toIntExact(notification.getUserId()));
                notification.setToNickName(toUser.getNickname());
            }
            if (notification.getArticleId() != null){
                Article byArticleId = articleService.getByArticleId(notification.getArticleId());
                if (byArticleId != null){
                    notification.setArticleTitle(byArticleId.getTitle());
                }
                else {
                    notification.setArticleTitle("文章已删除");
                }
            }

        }
        return notifications;
    }

    @Override
    public Integer total(String type,Integer userId,Integer isRead) {
        return notificationsMapper.total(type,userId,isRead);
    }

    @Override
    public Boolean isUnread(Integer userId) {
        return notificationsMapper.total(null,userId,0) > 0;
    }

    @Override
    public void read(Integer notificationId) {
        notificationsMapper.read(notificationId);
    }

    @Override
    public void readAll(Integer userId) {
        notificationsMapper.readAll(userId);
    }

    @Override
    public void add(Notifications notifications) {
        notificationsMapper.insertSelective(notifications);
    }

    @Override
    public void delete(Integer id) {
        notificationsMapper.deleteById(id);
    }
}
